#include "src/view.h"
#include <string>

#include "res/resource.h"
#include "utils/log.h"
#include "utils/base64/base64.h"

std::string GetDlgItemString(HWND hdlg, int id) {
    int buff_size = 512;
    int len       = 0;
    char *buff    = NULL;

    std::string ret;
    do {
        buff = new char[buff_size];
        len  = GetDlgItemTextA(hdlg, id, buff, buff_size);
        if (len == 0) {
            break;
        }

        if (len < buff_size) {
            ret = std::string(buff, len);
            break;
        }

        delete[] buff;
        buff_size *= 2;

    } while (true);
    if (buff) {
        delete[] buff;
    }
    return ret;
}

void OnInitDlg(HWND hdlg) {
    int w = GetSystemMetrics(SM_CXSCREEN);
    int h = GetSystemMetrics(SM_CYSCREEN);

    int center_x = w / 2;
    int center_y = h / 2;

    RECT rect;
    GetWindowRect(hdlg, &rect);

    int width  = rect.right - rect.left;
    int heigth = rect.bottom - rect.top;

    int left = center_x - (width / 2);
    int top  = center_y - (heigth / 2);

    log_info("dlg window width:%d, height:%d", width, heigth);

    SetWindowPos(hdlg, NULL, left, top, width, heigth, 0);
}

void OnClickedBtnEncode(HWND hdlg) {
    std::string input = GetDlgItemString(hdlg, IDC_EDIT1);
    log_info("encode:[%s]", input.c_str());
    std::string output;
    utils::Base64Encode(input, &output);
    SetDlgItemTextA(hdlg, IDC_EDIT2, output.c_str());
}

void OnClickedBtnDecode(HWND hdlg) {
    std::string input = GetDlgItemString(hdlg, IDC_EDIT1);
    log_info("decode:[%s]", input.c_str());
    std::string output;
    utils::Base64Decode(input, &output);
    SetDlgItemTextA(hdlg, IDC_EDIT2, output.c_str());
}

void OnClickedBtnSwap(HWND hdlg) {
    std::string s1 = GetDlgItemString(hdlg, IDC_EDIT1);
    std::string s2 = GetDlgItemString(hdlg, IDC_EDIT2);
    SetDlgItemTextA(hdlg, IDC_EDIT1, s2.c_str());
    SetDlgItemTextA(hdlg, IDC_EDIT2, s1.c_str());
}

void OnCommand(HWND hdlg, WPARAM wparam) {
    auto id = LOWORD(wparam);
    // auto event = HIWORD(wparam);
    switch (id) {
    case IDC_BTN_ENCODE:
        OnClickedBtnEncode(hdlg);
        break;
    case IDC_BTN_DECODE:
        OnClickedBtnDecode(hdlg);
        break;
    case IDC_BTN_SWAP:
        OnClickedBtnSwap(hdlg);
        break;
    default:
        break;
    }
}
